package f.h.dragon.patterns.gateway;

import java.util.ArrayList;
import java.util.List;

/**
 * MessageGatewayStub: for test
 *
 * @author Wenlong Meng(wenlong.meng@gmail.com)
 * @version 1.0 at 2012/04/23
 * @since 1.0
 */
public class MessageGatewayStub extends MessageGateway {
	
	//local variables
	/**
	 * flag: fail all message
	 */
	private boolean shouldFailAllMessages = false;
	private int messagesSent = 0;
	
	//Logic
	/**
	 * send msg: override doSend for test
	 * 
	 * @param msgType
	 * @param args
	 * @return
	 */
	@Override
	protected int doSend(String msgType, Object[] args) {
		int returnCode = isMessageValid(msgType, args);
		if(returnCode == MessageSender.SUCCESS){
			messagesSent++;
		}
		return returnCode;
	}

	/**
	 * test send
	 * 
	 * @param msgType
	 * @param args
	 * @return
	 */
	private int isMessageValid(String msgType, Object[] args) {
		//fail
		if(this.shouldFailAllMessages){
			return -999;
		}
		
		//check message type
		if(!legalMessageTypes().contains(msgType)){
			return MessageSender.UNKNOWN_MESSAGE_TYPE;
		}
		
		//check args
		for(Object arg : args){
			if(arg == null){
				return MessageSender.NULL_PARAMETER;
			}
		}
		
		return MessageSender.SUCCESS;
	}

	/**
	 * legal message types
	 * 
	 * @return
	 */
	private List<String> legalMessageTypes() {
		List<String> result = new ArrayList<String>();
		result.add(CONFIRM);
		return result;
	}
	
	/**
	 * set fail all messages
	 */
	public void failAllMessages(){
		this.shouldFailAllMessages = true;
	}

	/**
	 * @return the messagesSent
	 */
	public int getMessagesSent() {
		return messagesSent;
	}

}
